package na.edu.polytechnic;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XMLHandlerLocation extends DefaultHandler {
   StringBuilder currentValue = new StringBuilder();
   ItemizedOverlayArray locations;
   String type, name, address, info,  picture, minigamedata, minigametype;   
   int lat, lon;

   public XMLHandlerLocation(ItemizedOverlayArray locations) {
      super();
      this.locations = locations;
   }
   
   // Called when tag starts 
   @Override
   public void startElement(final String uri, final String localName, final String qName,
         final Attributes attributes) throws SAXException {
      if (localName.equalsIgnoreCase("location")) { //new location
         type = attributes.getValue("type");
         name = null;
         address = null;
         info = null;
         picture = null;
         minigamedata = null;
         minigametype = null;
         lat = 0;
         lon = 0;
      }
      else if (localName.equalsIgnoreCase("geopoint")){
    	 try{
             lat = (int)(Double.valueOf(attributes.getValue("lat")) * 1E6);
             lon = (int)(Double.valueOf(attributes.getValue("lon")) * 1E6);
          } catch (final NumberFormatException e){
             System.out.println("Could not parse GeoPoint: "+ e);
          }
      }
      else if (localName.equalsIgnoreCase("minigame")){
         minigametype = attributes.getValue("type").trim();

     }
   }

   /** Called when tag closing ( ex:- <name>AndroidPeople</name>
    * -- </name> )*/
   @Override
   public void endElement(final String uri, final String localName, final String qName)
   throws SAXException {
      /** set value */
      if (localName.equalsIgnoreCase("name")) {
         name = currentValue.toString().trim();
      }
      else if (localName.equalsIgnoreCase("info")) {
         info = currentValue.toString().trim();
      }
      else if (localName.equalsIgnoreCase("address")) {
          address = currentValue.toString().trim();
       }
      else if (localName.equalsIgnoreCase("picture")) {
         picture = currentValue.toString().trim();
      }
      else if (localName.equalsIgnoreCase("minigame")) {
         minigamedata = currentValue.toString().trim();
      }
      else if (localName.equalsIgnoreCase("location")) { //end tag
         locations.addToCategory(new mOverlayItem(lat, lon, type, name, info, address, picture, minigametype, minigamedata));
      }
      currentValue.delete(0, currentValue.length());
   }

   /** Called to get tag characters ( ex:- <name>AndroidPeople</name>
    * -- to get AndroidPeople Character ) */
   @Override
   public void characters(final char[] ch, final int start, final int length)
   throws SAXException {
      currentValue.append(ch, start, length);
   }
}